package cn.teduymdj.jxc.service.impl;

import cn.teduymdj.jxc.ex.ServiceException;
import cn.teduymdj.jxc.mapper.CustomerReturnListGoodsMapper;
import cn.teduymdj.jxc.mapper.CustomerReturnListMapper;
import cn.teduymdj.jxc.pojo.dto.*;
import cn.teduymdj.jxc.pojo.entity.CustomerReturnList;
import cn.teduymdj.jxc.pojo.entity.CustomerReturnListGoods;
import cn.teduymdj.jxc.pojo.vo.CustomerReturnListGoodsListItemVO;
import cn.teduymdj.jxc.pojo.vo.CustomerReturnListListItemVO;
import cn.teduymdj.jxc.pojo.vo.CustomerReturnListStandardVO;
import cn.teduymdj.jxc.security.LoginPrincipal;
import cn.teduymdj.jxc.service.CustomerReturnListGoodsService;
import cn.teduymdj.jxc.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class CustomerReturnListGoodsServiceImpl implements CustomerReturnListGoodsService {

    public static final String[] PAID_STATE = {"未支付","已支付"};

    @Autowired
    CustomerReturnListMapper customerReturnListMapper;
    @Autowired
    CustomerReturnListGoodsMapper customerReturnListGoodsMapper;

    @Override
    public void save(CustomerReturnListAddNewDTO02 customerReturnListAddNewDTO02) {
        CustomerReturnListAddNewDTO customerReturnListAddNewDTO = new CustomerReturnListAddNewDTO();
        BeanUtils.copyProperties(customerReturnListAddNewDTO02, customerReturnListAddNewDTO);
        customerReturnListAddNewDTO.setUserId(getLoginInfo().getId());
        int count = customerReturnListMapper.countByNum(customerReturnListAddNewDTO02.getCustomerReturnNumber());
        if (count > 0) {
            throw new ServiceException(ServiceCode.ERR_CONFLICT, "单号已存在");
        }
        int row = customerReturnListMapper.insert(customerReturnListAddNewDTO);
        if (row != 1) {
            String message = "新增客户退货单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        List<CustomerReturnListGoodsAddNewDTO> goodsList =
                customerReturnListAddNewDTO02.getCustomerReturnListGoodsAddNewDTOs();
        goodsList.forEach(goods -> goods.setCustomerReturnListId(customerReturnListAddNewDTO.getId()));
        goodsList.forEach(goods -> {
            if (!goods.getPrice().multiply(new BigDecimal(goods.getNum())).equals(goods.getTotal())) {
                throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "新增失败,数据不匹配");
            }
        });
        int rows = customerReturnListGoodsMapper.insertBatch(
                goodsList);
        if (rows < 1) {
            String message = "新增客户退单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public List<CustomerReturnListListItemVO> getCustomerReturnlist
            (SelectConditionDTO selectConditionDTO) {
        List<CustomerReturnListListItemVO> list = customerReturnListMapper.listByCondition(selectConditionDTO);
        return list;
    }

    @Override
    public List<CustomerReturnListGoodsListItemVO> getCustomerReturnListGoodsByCustomerReturnListId(Long customerReturnListId) {
        List<CustomerReturnListGoodsListItemVO> list =
                customerReturnListGoodsMapper.listByReturnListId(customerReturnListId);
        return list;
    }

    @Override
    public void delete(Long customerReturnListId) {
        CustomerReturnListStandardVO queryResult =
                customerReturnListMapper.getStandardById(customerReturnListId);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "删除客户退货单失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int rows = customerReturnListMapper.deleteById(customerReturnListId);
        if (rows != 1) {
            String message = "删除客户退货单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
         rows = customerReturnListGoodsMapper.deleteByListId(customerReturnListId);
        if (rows < 1) {
            String message = "删除客户退货单商品失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public CustomerReturnList getCustomerReturnList(Long customerReturnListId) {
        return null;
    }

    @Override
    public Integer getCustomerReturnTotalByGoodsId(Long goodsId) {
        return null;
    }


    @Override
    public void setPaid(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setUnpaid(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public List<CustomerReturnListGoodsListItemVO> getCustomerReturnListGoods(
            SelectReturnCondition selectReturnCondition) {
        List<CustomerReturnListGoodsListItemVO> list =
                customerReturnListGoodsMapper.listByCondition(selectReturnCondition);
        return list;
    }

    private void updateEnableById(Long id, int isPaid) {
        CustomerReturnListStandardVO queryResult =
                customerReturnListMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "修改支付状态失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断状态是否冲突（当前已经是目标状态）
        if (queryResult.getIsPaid().equals(isPaid)) {
            String message = "修改支付失败，退货单已经处于" + PAID_STATE[isPaid] + "状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        CustomerReturnList returnList = new CustomerReturnList();
        returnList.setId(id);
        returnList.setIsPaid(isPaid);
        int rows = customerReturnListMapper.update(returnList);
        if (rows != 1) {
            String message = "修改支付失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    private LoginPrincipal getLoginInfo() {
        return (LoginPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
